package com.ts.enterprise.common.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaconsole.*;
import com.aliyun.teautil.Common;
import com.ts.enterprise.common.config.SmsManagerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component
public class SmsManagerBuilder {

	
	private static Lock _lock = new ReentrantLock();
	private static com.aliyun.dysmsapi20170525.Client client=null;
	
	@Autowired
	private SmsManagerConfig smc;

	private com.aliyun.dysmsapi20170525.Client createClient() {
		_lock.lock();
		if (client==null) {
			try {
				client=SmsUtil.createClient(smc.getAccessKeyId(),smc.getAccessKeySecret());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		_lock.unlock();
		return client;
	}
	public boolean sendAckStatus(String phone,String signName, String templateCode, Map<String,String> templateParam ) {
		boolean result=false;
		com.aliyun.dysmsapi20170525.Client c=this.createClient();
		if (c!=null) {
			SendSmsRequest request=null;
			try {
				request=SmsUtil.createRequest(phone,signName,templateCode, Common.toJSONString(templateParam));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (request!=null) {
				try {
					result=SmsUtil.sendAckStatus(c, request);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	public Map<String, String> sendAckInfo(String phone,String signName, String templateCode, Map<String,String> templateParam ) {
		Map<String, String> result=null;
		com.aliyun.dysmsapi20170525.Client c=this.createClient();
		if (c!=null) {
			SendSmsRequest request=null;
			try {
				request=SmsUtil.createRequest(phone,signName,templateCode, Common.toJSONString(templateParam));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (request!=null) {
				try {
					result=SmsUtil.sendAckInfo(c, request);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}
